<template>
  <div class="page-service-group">
    <Breadcrumb separator=">">
      <BreadcrumbItem href="/home/environment"><i class="ivu-icon ivu-icon-home"></i> 环境中心</BreadcrumbItem>
      <BreadcrumbItem :href="'/home/environment/' + $route.params.environmentId" :title="'环境（' + envName + '）'">
        <i class="ivu-icon ivu-icon-aperture"></i> {{envName}}
      </BreadcrumbItem>
      <BreadcrumbItem
        :href="'/home/environment/' + $route.params.environmentId + '/' + $route.params.serviceGroup" :title="'服务组（' + groupName + '）'">
        <i class="ivu-icon ivu-icon-ribbon-b"></i> {{groupName}}
      </BreadcrumbItem>
      <BreadcrumbItem :title="'服务（' + service.id + '）'">{{service.id}}</BreadcrumbItem>
    </Breadcrumb>

    <h4 class="zl-title">基本信息</h4>
    <div class="environment-info">
      <Spin fix v-if="isLoading"></Spin>
      <div class="environment-info-box" v-else>
        <Row :gutter="10">
          <Col span="6" class="f-nowrap"><span class="info-title">名称：</span>{{service.id}}</Col>
          <Col span="6" class="f-nowrap"><span class="info-title">状态：</span>
            <span v-if="service.status === 'active'" class="color-green">启用</span>
            <span v-else class="color-red">停用</span>
          </Col>
          <Col span="12"><span class="info-title">镜像地址：</span>{{service.image}}</Col>
          <Col span="6"><span class="info-title">容器数：</span>{{service.replicas}}</Col>
          <Col span="6"><span class="info-title">单节点服务：</span>
            <span v-if="service.replicas === 1">是</span>
            <span v-else>否</span>
          </Col>
          <Col span="12"><span class="info-title">启动策略：</span>{{service.restartPolicy}}</Col>
          <Col span="8"><span class="info-title">创建时间：</span>{{service.creationTimestamp}}</Col>
        </Row>
      </div>
    </div>

    <!-- 容器列表 -->
    <h4 class="zl-title">容器列表
      <div class="fr">
        <search placeholder="搜索容器" @change="searchPods"></search>
        <Button type="primary" @click="podCount(1)" class="button-add" :loading="isAddLoading">
          <i class="iconfont icon-plus"></i>
          <span class="button-name">添加容器</span>
        </Button>
        <Button type="warning" @click="podCount(-1)" class="button-add" :loading="isMinusLoading" :disabled="podList.length <= 1">
          <i class="iconfont icon-minus-sign"></i>
          <span class="button-name">减少容器</span>
        </Button>
      </div>
    </h4>
    <div class="zl-page-loading" v-if="isLoading">
      <Spin class="zl-page-loading" fix></Spin>
    </div>
    <Table :columns="columns" :data="podList" class="pod-table" v-else></Table>

  </div>
</template>

<script>
  import Search from '@/components/search'
  import Fetch from '@/api/request'
  export default {
    name: 'service',
    components: {Search},
    data() {
      return {
        serviceId: '',
        service: {},
        envName: '',
        groupName: '',
        isLoading: false,
        isAddLoading: false,
        isMinusLoading: false,
        podList: [],
        podListBack: [],
        serviceVisible: false,
        columns: [{
          type: 'index',
          width: 70
        }, {
          title: '名称',
          key: 'id'
        }, {
          title: 'IP地址',
          render: (h, params) => {
            return h('span', params.row.status.podIP)
          }
        }, {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('i', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px',
                  cursor: 'pointer'
                },
                class: 'iconfont icon-trash',
                on: {
                  click: () => {
                    this.podDelete(params.row)
                  }
                }
              }, '')
            ])
          }
        }],
        prePodNum: -1 // 用于在改变容器数量时保存改变前容器数量值
      }
    },
    mounted() {
      this.envName = this.$route.params.environmentId
      this.groupName = localStorage.getItem('serviceGroup')
      this.init()
    },
    methods: {
      // 初始化
      init() {
        this.getServiceInfo()
        this.getPods()
      },
      // 获取服务基本信息
      getServiceInfo() {
        Fetch.get({
          url: '/api/service/info',
          params: {
            environmentId: this.$route.params.environmentId,
            serviceId: this.$route.params.service
          }
        }).then((res) => {
          if (res && res.code === '0') {
            this.service = res.data
          } else {
            this.$Message.warning({
              content: res.message || '服务器内部错误',
              duration: this.DURATION
            })
          }
        }).catch((err) => {
          this.$Message.error(err.message)
        })
      },
      // 获取服务下容器信息
      getPods() {
        Fetch.get({
          url: '/api/getPods',
          params: {
            environmentId: this.$route.params.environmentId,
            groupId: this.$route.params.serviceGroup,
            serviceId: this.$route.params.service
          }
        }).then((res) => {
          if (res && res.code === '0') {
            this.podList = res.data
            if (this.podList.length === this.prePodNum) {
              setTimeout(() => {
                this.getPods()
              }, 2000)
            }
            this.podListBack = res.data
          } else {
            this.$Message.warning({
              content: res.message || '服务器内部错误',
              duration: this.DURATION
            })
          }
        }).catch((err) => {
          this.$Message.error(err.message)
        })
      },
      podDelete(pod) {
        this.$Modal.confirm({
          title: '系统提示',
          content: '<div style="padding: 30px; text-align: center;">确定删除容器？</div>',
          loading: true,
          onOk: () => {
            Fetch.delete({
              url: '/api/pod/delete',
              params: {
                environmentId: this.$route.params.environmentId,
                podId: pod.id
              }
            }).then((res) => {
              if (res && res.code === '0') {
                this.$Message.success({
                  content: '删除容器成功！',
                  duration: this.DURATION
                })
                setTimeout(() => {
                  this.getPods()
                }, 500)
              } else {
                this.$Message.warning({
                  content: res.message || '服务器内部错误',
                  duration: this.DURATION
                })
              }
              this.$Modal.remove()
            }).catch((err) => {
              this.$Modal.remove()
              this.$Message.error(err.message)
            })
          }
        })
      },
      // 修改容器数量
      podCount(offset) {
        this.prePodNum = this.podList.length
        offset > 0 ? this.isAddLoading = true : this.isMinusLoading = true
        Fetch.patch({
          url: '/api/pod/add',
          params: {
            environmentId: this.$route.params.environmentId,
            groupId: this.$route.params.serviceGroup,
            serviceId: this.$route.params.service,
            data: {
              patchType: 'replicas',
              replicas: this.service.replicas + offset
            }
          }
        }).then((res) => {
          if (res && res.code === '0') {
            this.$Message.success({
              content: offset > 0 ? '新增容器成功！' : '减少容器成功！',
              duration: this.DURATION
            })
            setTimeout(() => {
              this.getPods()
            }, 500)
          } else {
            this.$Message.warning({
              content: res.message || '服务器内部错误',
              duration: this.DURATION
            })
          }
          offset > 0 ? this.isAddLoading = false : this.isMinusLoading = false
        }).catch((err) => {
          this.$Message.error(err.message)
          offset > 0 ? this.isAddLoading = false : this.isMinusLoading = false
        })
      },
      // 根据名称搜索服务组
      searchPods(search) {
        let temp = []
        this.podListBack.forEach((pod) => {
          let name = pod.id
          if (name.indexOf(search) !== -1) {
            temp.push(pod)
          }
        })
        this.podList = temp
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .environment-info {
    position: relative;
    min-height: 100px;
  }
  .environment-info-box {
    line-height: 32px;
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    border: 1px solid #eee;
  }
  .modal-add {
    position: relative;
    padding: 10px 50px 10px 20px;
  }
  .button-add {
    .iconfont:hover {
      color: #fff;
    }
    + .button-add {
      margin-left: 10px;
    }
  }
  .pod-table {
    margin-top: 20px;
  }
</style>
